package org.example.Servlet.PersonServlet;

import cn.hutool.json.JSONUtil;
import org.example.Dao.PersonDao;
import org.example.entity.Person;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/admin/person/find")
public class FindPersonServlet extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        int pid = 0;
        if (req.getParameter("pid").isEmpty()) {
            pid = -1;
        } else {
            pid = Integer.parseInt(req.getParameter("pid"));
        }

        String email = req.getParameter("email");
        String username = req.getParameter("username");
        // 日期字符串转换成日期
        String beginDateStr = req.getParameter("beginDate");
        String endDateStr = req.getParameter("endDate");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        PersonDao personDao = new PersonDao();
        Date beginDate = null;
        Date endDate = null;
        try {

            if (!beginDateStr.isEmpty()) {
                beginDate = simpleDateFormat.parse(beginDateStr);
            }

            if (!endDateStr.isEmpty()) {
                endDate = simpleDateFormat.parse(endDateStr);
            }
            session.setAttribute("findPersonMsg", "");
            List<Person> personList = personDao.findPerson(pid, username, email, beginDate, endDate);
            resp.getWriter().write(JSONUtil.toJsonStr(personList));
        } catch (Exception e) {
            System.out.println("find person error ==> " + e.getMessage());
            session.setAttribute("findPersonMsg", "刚才溜号了");
            req.getRequestDispatcher(req.getContextPath() + "/views/admin/findPerson").forward(req, resp);
        }

    }
}
